640. 求解方程
为保证权益,题目请参考 640. 求解方程(From LeetCode).
解决方案1
Python
python
# 640. 求解方程
# https://leetcode.cn/problems/solve-the-equation/
from typing import Tuple
class Solution:
def solveEquation(self, equation: str) -> str:
def parse(equation: str) -> Tuple[int, int]:
x1 = 0
x0 = 0
item_start_idx = 0
item_exp = "+"
get_eq = False
for i in range(len(equation)):
if equation[i] in ["+", "-", "="]:
if i - item_start_idx == 0:
item_start_idx = i + 1
item_exp = equation[i]
continue
item = equation[item_start_idx:i]
item_start_idx = i + 1
if "x" in item:
if len(item[:-1]) == 0:
item_val = 1
else:
item_val = int(item[:-1])
if (item_exp == "+") ^ get_eq:
x1 += item_val
else:
x1 -= item_val
else:
if (item_exp == "+") ^ get_eq:
x0 += int(item)
else:
x0 -= int(item)
if equation[i] == "=":
get_eq = True
item_exp = "+"
else:
item_exp = equation[i]
item = equation[item_start_idx:]
if "x" in item:
if len(item[:-1]) == 0:
item_val = 1
else:
item_val = int(item[:-1])
if (item_exp == "+") ^ get_eq:
x1 += item_val
else:
x1 -= item_val
else:
if (item_exp == "+") ^ get_eq:
x0 += int(item)
else:
x0 -= int(item)
return x1, x0
x1, x0 = parse(equation)
if x1 == 0:
if x0 == 0:
return "Infinite solutions"
else:
return "No solution"
else:
return "x={}".format(-x0 // x1)
if __name__ == "__main__":
so = Solution()
print(so.solveEquation("x+5-3+x=6+x-2"))
print(so.solveEquation("x=x"))
print(so.solveEquation("2x=x"))
print(so.solveEquation("-x=-1"))
print(so.solveEquation("-x=-345"))
print(so.solveEquation("-x=-1"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84